package com.wowocai.btchina.utils;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.springframework.util.Assert;

/**
 * Created by liufanping on 2016/12/29.
 */
public class TimeUtils {

	public static final String TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ssZ";

	public static long getUTCTime() {
		Calendar calendar = Calendar.getInstance();
		int offset = calendar.get(Calendar.ZONE_OFFSET);
		calendar.add(Calendar.MILLISECOND, -offset);
		return calendar.getTimeInMillis();
	}

	public static void main(String[] args) {
		System.out.println(now());
	}

	public static long diff(final long timeA, final long timeB) {
		return Math.abs(timeA - timeB);
	}

	public static String now() {
		return now(TIME_FORMAT);
	}

	public static String now(String format) {
		Assert.notNull(format, "时间格式不能为空");
		Calendar ca = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"), Locale.ENGLISH);
		SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
		return format(ca.getTime(), sdf);
	}

	public static String format(Date date) {
		return format(date, TIME_FORMAT);
	}

	public static String format(Date date, DateFormat format) {
		if (date == null)
			return null;
		Assert.notNull(format, "时间格式不能为空");
		return format.format(date);
	}

	public static String format(Date date, String format) {
		if (date == null) {
			return null;
		}
		if (format == null) {
			return null;
		}
		DateFormat format_ = new SimpleDateFormat(format);
		return format_.format(date);
	}

	public static Date parse(String date, String format) {
		if (date == null) {
			return null;
		}
		if (format == null) {
			return null;
		}
		DateFormat format_ = new SimpleDateFormat(format);
		return parse(date, format_);
	}

	public static Date parse(String date, DateFormat format) {
		if (date == null) {
			return null;
		}
		if (format == null) {
			return null;
		}
		try {
			return format.parse(date);
		} catch (ParseException e) {
			return null;
		}
	}
}
